/**
 * 从服务端获取文件流
 */
//import
import {aesEncryptAllParams} from '@/base/AesEncrptUtil';
import Storage from '@/base/storage';
import {getRandomStr} from '@/base/utils'

export default class ImageObj {

    constructor(url){
        //请求服务端的图片流路径
        this.url = '/xsb/personBusiness/file/h5imageServletNew';
        if(url){
            this.url = url;
        }

    }
    //处理请求参数和URL
    dealUrl(attachId,reqParam){
        let retUrl = `${this.url}?attachId=${attachId}`;
        if(reqParam && typeof reqParam == 'object'){
            for (let key in reqParam){
                let value = reqParam[key];
                retUrl += `&${key}=${value}`;
            }
        }
        retUrl = Storage.get('webUrl') + aesEncryptAllParams(retUrl);
        return retUrl;
    }

    setRequestHeader(request){
        let uinfo =  Storage.session.get('userInfo');
        let tokenId = uinfo.tokenid;//token
        let aldregion = uinfo.region+'_'+uinfo.servNumber;//用于区分在哪个中心
        let imei = uinfo.imei || '-1';
        let operaterPhone = uinfo.servNumber;
        request.setRequestHeader('tokenid', tokenId);
        request.setRequestHeader('aldregion', aldregion);
        request.setRequestHeader('imei', imei);
        request.setRequestHeader('operaterPhone', operaterPhone);
        request.setRequestHeader('c03be90046a7e7f','GwRT4HjrxC9Davw');
        // request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    }

    //xmlHttpRequest请求图片流
    reqImage(attachId,reqParam){
        let url = this.dealUrl(attachId,reqParam);
        let request = new XMLHttpRequest();

        request.open('get', url, true);
        request.responseType = 'blob';
        this.setRequestHeader(request);//设置请求头
        return new Promise((resolve, reject) => {
            request.onreadystatechange = e => {
                if (!request || request.readyState !== XMLHttpRequest.DONE) {
                    return;
                }
                // 请求出错，我们没有得到响应，这将由oneror处理
                //除了一个例外：使用file:protocol的请求，大多数浏览器将返回状态为0，即使这是一个成功的请求
                if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
                    return;
                }
                if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
                    return resolve(request.response)
                } else {
                    console.info('--reject----')
                    return reject(Error('图片加载失败'));//图片流加载失败
                }
            };

            request.onerror = ()=>{
                let resError = reject(Error('获取图片发生网络错误'));
                reuest = null;
                return resError;
            }
            request.send(null);
        })
    }

    /**
     * 设置img的图片
     * @param {img标签的dom} imgDom
     * @param {图片附件ID} attachId
     * @param {额外的请求参数} reqParam
     * @param {不是默认的服务端请求} url
     * @returns
     */
    static setImgToDom(imgDom,attachId,reqParam,url){
        if(!imgDom){
            return;
        }
        let instance = new ImageObj(url);
        instance.reqImage(attachId,reqParam).then(res=>{
            imgDom.src = URL.createObjectURL(res);
            imgDom.onload = () => {
                URL.revokeObjectURL(imgDom.src);
            }
        }).catch(e=>{
            console.error('动态设置img的图片',e)
        });
    }

    /**
     * 获取图片流对象
     * @param {图片附件ID} attachId
     * @param {额外的请求参数} reqParam
     * @param {不是默认的服务端请求} url
     */
    static getImgUrl(attachId,reqParam,url){
        let instance = new ImageObj(url);
        return new Promise((resolve,reject) =>{
            instance.reqImage(attachId,reqParam).then((res)=>{
                //返回当前文件的一个内存URL
                resolve(URL.createObjectURL(res));
            }).catch(res=>{
                reject(res);
            });
        });
    }

  /**
   * 获取图片base64编码字符串
   * @param {图片附件ID} attachId
   * @param {额外的请求参数} reqParam
   * @param {不是默认的服务端请求} url
   */
    static getImgBase64Str(attachId, reqParam, url) {
      let instance = new ImageObj(url);
      return new Promise((resolve,reject) =>{
        instance.reqImage(attachId,reqParam).then((res)=>{
          // 创建一个 FileReader 对象
          const reader = new FileReader();
          // 读取回调
          reader.onload = event => {
            resolve(event.target.result);
          }
          // 开始读取 Blob 对象
          reader.readAsDataURL(res);
        }).catch(res=>{
          reject(res);
        });
      });
    }
}
